#!/bin/bash
# Copyright 2019-2024 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================

set -e

BASEPATH=$(cd "$(dirname $0)/.."; pwd)
OUTPUT_PATH="${BASEPATH}/output"
BUILD_PATH="${BASEPATH}/build/"

# print usage message
usage() {
  echo "Usage:"
  echo "  sh run_test.sh [-u | --ut] [-s | --st] [-c | --cov] [-j<N>] [-h | --help] [-v | --verbose]"
  echo "                 [--ascend_custom_path=<PATH>]"
  echo ""
  echo "Options:"
  echo "    -h, --help     Print usage"
  echo "    -u, --ut       Build ut"
  echo "    -s, --st       Build st"
  echo "    -c, --cov      Build ut and st with coverage tag"
  echo "    -v, --verbose  Display build command"
  echo "    -j<N>          Set the number of threads used for building Parser llt, default 8"
  echo "        --ascend_custom_path=<PATH>"
  echo "                   Set ascend package install path, default /usr/local/Ascend/latest"
  echo "                   Set build metadef or use released package, default on"
  echo ""
}

# check value of input is 'on' or 'off'
# usage: check_on_off arg_value arg_name
check_on_off() {
  arg_value="$(echo $1 | tr '[A-Z]' '[a-z]')"
  if [ "X$arg_value" != "Xon" ] && [ "X$arg_value" != "Xoff" ]; then
    echo "Invalid value $arg_value for option -$2"
    usage
    exit 1
  fi
}

# parse and set options
checkopts() {
  VERBOSE=""
  THREAD_NUM=8
  ENABLE_PARSER_UT="off"
  ENABLE_PARSER_ST="off"
  ENABLE_PARSER_COV="off"
  ENABLE_GITEE="off"
  ASCEND_CUSTOM_PATH="/usr/local/Ascend/latest"
  BUILD_METADEF="on"

  parsed_args=$(getopt -a -o uscj:hv -l ut,st,cov,help,verbose,ascend_custom_path: -- "$@") || {
    usage
    exit 1
  }

  eval set -- "$parsed_args"

  while true; do
    case "$1" in
      -u | --ut)
        ENABLE_PARSER_UT="on"
        shift
        ;;
      -s | --st)
        ENABLE_PARSER_ST="on"
        shift
        ;;
      -c | --cov)
        ENABLE_PARSER_COV="on"
        shift
        ;;
      -h | --help)
        usage
        exit 0
        ;;
      -j)
        THREAD_NUM="$2"
        shift 2
        ;;
      -v | --verbose)
        VERBOSE="VERBOSE=1"
        shift
        ;;
      --ascend_custom_path)
        ASCEND_CUSTOM_PATH="$2"
        shift 2
        ;;
      --)
        shift
        break
        ;;
      *)
        echo "Undefined option: $1"
        usage
        exit 1
        ;;
    esac
  done
}

mk_dir() {
  local create_dir="$1"  # the target to make
  mkdir -pv "${create_dir}"
  echo "created ${create_dir}"
}

# create build path
build_parser() {
  echo "create build directory and build Parser llt";
  echo "ENABLE_PARSER_UT = " ${ENABLE_PARSER_UT}
  echo "ENABLE_PARSER_ST = " ${ENABLE_PARSER_ST}
  echo "ENABLE_PARSER_COV = " ${ENABLE_PARSER_COV}
  mk_dir "${BUILD_PATH}"
  cd "${BUILD_PATH}"
  cmake -D ENABLE_OPEN_SRC=True \
        -D ENABLE_PARSER_COV=${ENABLE_PARSER_COV} \
        -D ENABLE_PARSER_UT=${ENABLE_PARSER_UT} \
        -D ENABLE_PARSER_ST=${ENABLE_PARSER_ST} \
        -D ENABLE_GITEE=${ENABLE_GITEE} \
        -D BUILD_METADEF=${BUILD_METADEF} \
        -D BUILD_WITHOUT_AIR=True \
        -D ASCEND_CUSTOM_PATH=${ASCEND_CUSTOM_PATH} \
        -D CMAKE_BUILD_TYPE=Release \
        -D CMAKE_INSTALL_PREFIX=${OUTPUT_PATH} \
        ..
  if [ 0 -ne $? ]; then
    echo "execute command: cmake .. failed."
    return 1
  fi

  if [ "X$ENABLE_PARSER_UT" = "Xon" ]; then
    make ut_parser -j8
  fi
  if [ 0 -ne $? ]; then
    echo "execute command: make ut_parser failed."
    return 1
  fi

  if [ "X$ENABLE_PARSER_ST" = "Xon" ]; then
    make st_parser -j8
  fi
  if [ 0 -ne $? ]; then
    echo "execute command: make st_parser failed."
    return 1
  fi

  echo "Parser llt build success!"
}

main() {
  cd "${BASEPATH}"
  checkopts "$@"
  if [[ "X$ENABLE_PARSER_UT" != "Xon" || "X$ENABLE_PARSER_COV" != "Xon" ]]; then
    ENABLE_PARSER_UT="on"
    ENABLE_PARSER_ST="on"
    ENABLE_PARSER_COV="on"
  fi
  if [ "X$BUILD_METADEF" = "Xon" ]; then
    git submodule update --init metadef
  fi

  g++ -v
  mk_dir "${OUTPUT_PATH}"

  # Parser llt build start
  echo "---------------- Parser llt build start ----------------"
  build_parser || { echo "Parser llt build failed."; exit 1; }
  echo "---------------- Parser llt build finished ----------------"

  if [[ "X$ENABLE_PARSER_UT" = "Xon" ]]; then
    cp ${BUILD_PATH}/tests/ut/parser/ut_parser ${OUTPUT_PATH}

    RUN_TEST_CASE=${OUTPUT_PATH}/ut_parser && ${RUN_TEST_CASE}
    if [[ "$?" -ne 0 ]]; then
      echo "!!! UT FAILED, PLEASE CHECK YOUR CHANGES !!!"
      echo -e "\033[31m${RUN_TEST_CASE}\033[0m"
      exit 1
    fi
    if [[ "X$ENABLE_PARSER_COV" = "Xon" ]]; then
      echo "Generating coverage statistics, please wait..."
      cd "${BASEPATH}"
      rm -rf "${BASEPATH}/cov"
      mk_dir "${BASEPATH}/cov"
      lcov -c -d build/tests/ut/parser -o cov/tmp.info
      lcov -r cov/tmp.info '*/output/*' '*/build/opensrc/*' '*/build/proto/*' '*/third_party/*' '*/tests/*' '/usr/local/*' '*/metadef/inc/*' -o cov/coverage.info
      cd "${BASEPATH}/cov"
      genhtml coverage.info
    fi
  fi

  if [[ "X$ENABLE_PARSER_ST" = "Xon" ]]; then
    cp ${BUILD_PATH}/tests/st/st_parser ${OUTPUT_PATH}

    RUN_TEST_CASE=${OUTPUT_PATH}/st_parser && ${RUN_TEST_CASE}
    if [[ "$?" -ne 0 ]]; then
      echo "!!! ST FAILED, PLEASE CHECK YOUR CHANGES !!!"
      echo -e "\033[31m${RUN_TEST_CASE}\033[0m"
      exit 1
    fi
    if [[ "X$ENABLE_PARSER_COV" = "Xon" ]]; then
      echo "Generating coverage statistics, please wait..."
      cd "${BASEPATH}"
      rm -rf "${BASEPATH}/cov"
      mk_dir "${BASEPATH}/cov"
      lcov -c -d build/tests/st -o cov/tmp.info
      lcov -r cov/tmp.info '*/output/*' '*/build/opensrc/*' '*/build/proto/*' '*/third_party/*' '*/tests/*' '/usr/local/*' '*/metadef/inc/*' -o cov/coverage.info
      cd "${BASEPATH}/cov"
      genhtml coverage.info
    fi
  fi

  echo "---------------- Parser llt finished ----------------"
}

main "$@"
